package com.kangjia.model.m1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kangjia.general.dao.GeneralDao;
import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.model.m0.entity.Role;
import com.kangjia.model.m1.entity.Depart;
import com.kangjia.model.m1.entity.Employee;
import com.kangjia.model.m1.entity.Org;
import com.kangjia.model.m1.entity.Store;

@Service
public class EmployeeService {

	@Autowired
	private GeneralDao generalDao;

	public String create(Employee employee) {
		Role role = generalDao.get(Role.class, employee.getRoleId());
		String authority = null;
		if (role != null && role.getStatus().equals(0)) {
			authority = role.getAuthority();
		}
		employee.setAuthority(authority);

		if (employee.getDeptId() != null) {
			Depart depart = generalDao.get(Depart.class, employee.getDeptId());
			if (depart != null) {
				employee.setDeptCode(depart.getCode());
			}
		}
		
		if (employee.getOrgId() != null) {
			Org org = generalDao.get(Org.class, employee.getOrgId());
			if (org != null) {
				employee.setOrgCode(org.getCode());
			}
		}

		try {
			return DataMapper.getInstance().writeValueAsString(employee);
		} catch (JsonProcessingException e) {
			return null;
		}
	}

	public Employee queryByLogin(String login) {
		QueryParam params = new QueryParam();
		params.addParam(new Param<String>("login", OperType.eq, login));
		Employee entity = generalDao.sign(Employee.class, params);
		return entity;
	}

	public void update(Employee entity) {
		generalDao.saveOrUpdate(entity);
	}

	public boolean exist(String login) {
		QueryParam params = new QueryParam();
		params.addParam(new Param<String>("login", OperType.eq, login));
		Integer count = generalDao.count(Employee.class, params);
		return count != null && count > 0 ? true : false;
	}

	public void getOrgAndStore(Employee employee) {
		if (employee.getOrgId() != null) {
			Org org = generalDao.get(Org.class, employee.getOrgId());
			if (org != null) {
				employee.setOrgName(org.getOrgName());
			}
		}
		if (employee.getStoreId() != null) {
			Store store = generalDao.get(Store.class, employee.getStoreId());
			if (store != null) {
				employee.setStoreName(store.getCname());
			}
		}
		if (employee.getRoleId() != null) {
			Role role = generalDao.get(Role.class, employee.getRoleId());
			if (role != null) {
				employee.setRoleName(role.getRoleName());
			}
		}
	}
}
